package se.webbzon.boltzmann.game;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import se.webbzon.oschi01.utilities.FileUtils;

public class LocalGameManager implements GameManager {
	
	// The extension used for bass files
	private static final String bassExtension = "bass";
	
	// A list of all the available games
	private final List<LocalGame> games;
	
	/*============================================================
	Constructors
	============================================================*/
	
	public LocalGameManager() {
		games = new ArrayList<LocalGame>();
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	@Override public void refresh() throws Exception {
		URI uri = LocalGameManager.class.getProtectionDomain().getCodeSource().getLocation().toURI();
		File runnableFile = new File(uri);
		File gameDirectory = new File(runnableFile.getParentFile(),"games");
		games.clear();
		if (gameDirectory.exists()) {
			File[] files = gameDirectory.listFiles();
			for (File game : files) {
				if (FileUtils.getExtension(game.getName()).toLowerCase().equals(bassExtension))
					games.add(new LocalGame(game));
			}
		}
	}

	@Override public int maxGames() {
		return -1;
	}

	@Override public int games() {
		return games.size();
	}

	@Override public Game getGame(int n) {
		return games.get(n);
	}

	@Override public Game createGame(String name) {
		LocalGame game = new LocalGame(name);
		if (games.add(game)) {
			return game;
		} else
			return null;
	}

	@Override public boolean removeGame(int n) {
		return games.get(n).removeGame();
	}

}
